/**
 * <p>Project: questionnaire</p>
 * <p>Copyright: Copyright (c) 2015 7dub.cn</p>
 * <p>Company: 柒色都吧7dub.cn</p>
 */

package cn.dub.service.show.impl;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import cn.dub.common.utils.Clock;
import cn.dub.common.utils.CurrentUserUtils;
import cn.dub.common.utils.EncryptUtils;
import cn.dub.common.utils.IdUtils;
import cn.dub.dao.show.IUserMybatisDao;
import cn.dub.entity.show.User;
import cn.dub.entity.show.User.Gender;
import cn.dub.form.show.session.EditForm;
import cn.dub.form.show.session.RegisterForm;
import cn.dub.service.show.IUserService;

/**
 * 用户业务逻辑实现。
 *
 * @author CaoZhongsheng(2015年3月12日 下午5:08:09)
 *
 * @since 1.0.0
 *
 * @version 1.0.0
 *
 */
@Service
public class UserServiceImpl implements IUserService {

    @Inject
    private IUserMybatisDao userDao;

    private Clock clock = Clock.DEFAULT;

    public void setClock(Clock clock) {
        this.clock = clock;
    }

    @Override
    public boolean insert(RegisterForm form) {
        String email = form.getEmail(); //
        String password = form.getPassword(); //
        String rePassword = form.getRePassword(); //
        boolean success = Boolean.FALSE;

        if (rePassword.equalsIgnoreCase(password)) {
            User user = new User();
            user.setId(IdUtils.getId());
            user.setEmail(email);
            user.setPassword(EncryptUtils.encryptMD5(password));
            user.setCreateTime(this.clock.getCurrentTimeInMillis());
            success = this.userDao.insert(user) > 0;
        }
        return success;
    }

    @Override
    public User findByEmail(String email) {
        return this.userDao.selectByEmail(email);
    }

    @Override
    public boolean editCurrentUser(EditForm form) {
        String nickname = form.getNickname(); // 昵称
        String ageStr = form.getAge(); // 年龄
        Gender gender = Gender.valueOf(form.getGender()); // 性别
        String address = form.getAddress(); // 地址
        String intro = form.getIntro(); // 介绍

        Integer age = 0;
        if (StringUtils.isNotBlank(ageStr)) {
            age = Integer.parseInt(ageStr);
        }

        String id = CurrentUserUtils.getCurrentUser().getId();

        return this.userDao.updateById(id, nickname, address, intro, age, gender.ordinal()) > 0;
    }
}
